<?php

namespace App\Http\Controllers\App;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\App\BaseController;
use App\Models\User;
use App\Models\Code;
use App\Baqi\Alimns\AliMnsMsg;

class UserController extends Controller
{
    /**
     * 注册
     *
     * @return json
     */
    public function reg(Request $request)
    {
        $tel      = $request->input('tel', '');
        $code     = $request->input('code', '');
        $password = $request->input('password', '');
        $nickname = $request->input('nickname', '');
        $tg_id    = $request->input('tg_id', 0);

        //手机验证处理
        if( empty( $tel ) ){

            return self::error('手机号码不可为空');

        }else{

            $userinfo = User::where('user_mobile', $tel)->first();

            if($userinfo) return self::error('手机已被注册');

        }

        //验证码有效期验证
        if( !empty($code) ){

           $check_res = Code::check_code($tel, $code, 'reg');

           if(!$check_res) return self::error('验证码已过期');

        }else{

            return self::error('验证码不可为空');

        }

        $user = new User;

        //密码加密处理
        if( !empty($password)){

            $pwd = $user->create_pwd($password);

        }else{

            return self::error('密码不可为空');

        }

        $user->user_name     = $tel;
        $user->user_mobile   = $tel;
        $user->user_pwd      = $pwd;
        $user->login_token   = $user->token($tel);
        $user->login_time    = time();
        $user->user_nickname = $nickname ? $nickname : $user->rand_char();
        $user->tg_id         = $tg_id;

        $user->save();

        $return = User::get_user_info($user);

        return self::json($return, '注册成功');
    }

    /**
     * 发送手机验证码
     *
     * @return json
     */
    public function login(Request $request)
    {
        $tel      = $request->input('tel', '');
        $password = $request->input('password', '');

        //手机验证处理
        if( empty( $tel ) ){

            return self::error('手机号码不可为空');

        }else{

            $userinfo = User::where('user_name', $tel)->first();

        }

        if($userinfo){

            $res = User::check_pwd($password, $userinfo->user_pwd);

            if($res){

                if($userinfo->status == 2) return self::error('该用户已被禁止登录');
                //登录token更新
                $token = User::token($tel);

                User::where('id', $userinfo->id)->update(['login_token'=>$token, 'login_time'=>time()]);

                $userinfo->login_token = $token;

                $return = User::get_user_info($userinfo);

                return self::json($return, '登录成功');

            }else{

                return self::error('用户密码不匹配');

            }

        }else{

            return self::error('该用户未注册');

        }
    }
    
    /**
     *  找回重置密码
     *
     * @return json
     */
    public function update_pwd(Request $request)
    {
        $tel      = $request->input('tel', '');
        $code     = $request->input('code', '');
        $password = $request->input('password', '');

        //手机验证处理
        if( empty( $tel ) ){

            return self::error('手机号码不可为空');

        }else{

            $user = User::where('user_mobile', $tel)->first();

            if(!$user) return self::error('手机未注册');

        }

        //验证码有效期验证
        if( !empty($code) ){

           $check_res = Code::check_code($tel, $code, 'find');

           if(!$check_res) return self::error('验证码错误或过期');

        }else{

            return self::error('验证码不可为空');

        }

        //密码加密处理
        if( !empty($password)){

            $pwd = $user->create_pwd($password);

        }else{

            return self::error('密码不可为空');

        }

        $user->user_pwd      = $pwd;
        $user->login_token   = $user->token($tel);

        $user->save();

        //$return = User::get_user_info($user);

        return self::success('重置密码成功');

    }

    /**
     * 改变手机号
     *
     * @return json
     */
    public function update_tel(Request $request)
    {
        $tel      = $request->input('tel', '');
        $code     = $request->input('code', '');
        $user_id  = session('user_id');

        if(!$user_id) return self::error('用户未登录');

        //手机验证处理
        if( empty( $tel ) ){

            return self::error('手机号码不可为空');

        }else{

            $user = User::where('user_mobile', $tel)->first();

            if($user) return self::error('手机已被绑定');

        }

        //验证码有效期验证
        if( !empty($code) ){

           $check_res = Code::check_code($tel, $code, 'bind');

           if(!$check_res) return self::error('验证码错误或过期');

        }else{

            return self::error('验证码不可为空');

        }

        $user = User::find($user_id);

        $user->user_name     = $tel;
        $user->user_mobile   = $tel;

        $user->save();

        return self::success('手机绑定成功');
    }

    /**
     * 修改个人资料
     *
     * @return json
     */
    public function update_user_info(Request $request)
    {
        $user_id  = session('user_id');

        if(!$user_id) return self::error('用户未登录');

        $user = User::find($user_id);

        //设置昵称
        if($request->input('nickname')){

            $value = trim($request->input('nickname'));

            $user->user_nickname = $value;
        }

        //设置年龄
        if($request->input('age')){

            $value = trim($request->input('age'));

            $user->user_age = $value;
        }

        //设置年龄
        if($request->input('sex')){

            $value = trim($request->input('sex'));

            $value = $value == 1 ? $value : 0;
            
            $user->user_sex = $value;
        }

        //设置常驻地
        if($request->input('avatar')){

            $value = trim($request->input('avatar'));

            $user->user_avatar = $value;
        }

        $user->save();

        return self::success('设置成功');

    }

    /**
     * 个人中心
     *
     * @return json
     */
    public function personal_center(Request $request)
    {
        $user_id  = session('user_id');

        if(!$user_id) return self::error('用户未登录');

        $info = User::find($user_id);

        $return = [];

        if($info){

            $return['id']       = $info->id;
            $return['nickname'] = $info->user_nickname;
            $return['sex']      = $info->user_sex;
            $return['age']      = $info->user_age; 
            $return['avatar']   = asset($info->user_avatar);

        }
        

        return self::json($return);
    }

    /**
     * 发送手机验证码
     *
     * @return json
     */
    public function sms(Request $request)
    {
        $to   = $request->input('tel', '');
        $type = $request->input('type', '');

        if(empty($to)){

            return self::error('手机号码不可为空');

        }

        //验证码保存入库
        $code = (string)mt_rand(1000,9999);

        //验证发送类型 获取不同模版
        switch ($type) {
            case 'login':
                $type = 'login';
                $sql_type = 1;
                break;

            case 'find':
                $type = 'find';
                $sql_type = 2;
                break;

            case 'bind':
                $type = 'bind';
                $sql_type = 3;
                break;

            case 'update':
                $type = 'update';
                $sql_type = 4;
                break;

            case 'update_pay':
                $type = 'update_pay';
                $sql_type = 5;
                break;

            default:
                $type = 'reg';
                $sql_type = 0;
                break;
        }

        $info = Code::where('mobile', $to)->where('type', $sql_type)->value('updated_at');
        
        $time = strtotime($info);

        if( (time()-$time) < 60 ){

            return self::error('请求频繁，60秒后可再次发起请求');

        }

        //存在更新 不存在入库 （每个手机号每种类型只保存一个验证码）
        Code::updateOrCreate(['mobile' => $to, 'type' => $sql_type], ['mobile' => $to, 'code' => $code, 'type' => $sql_type]);
        
        $smss = new AliMnsMsg;

        //手机号和验证码必须是string
        $result = $smss->send_sms($to, $code, $type);

        if($result == true){

            return self::success('验证码发送成功');

        }else{

            return self::error('验证码发送失败');

        }

    }

    /**
     * 修改支付密码
     *
     * @param Request $request
     * @return void
     */
    public function editPayPwd( Request $request )
    {
        $tel  = $request->input('tel');
        $code = $request->input('code');
        $pwd  = $request->input('pwd');
        $pwd1 = $request->input('pwd1');

        if( !empty($code) ){

           $check_res = Code::check_code($tel, $code, 'update_pay');

           if(!$check_res) return self::error('验证码错误或过期');

        }else{

            return self::error('验证码不可为空');

        }
        
        if ( !$pwd ) {
            return self::error( '密码不能为空' );
        }

        if ( $pwd != $pwd1 ) {
            return self::error( '两次密码不一致' );
        }

        $info = User::where('user_mobile', $tel)->first();

        if ( !$info ) {
            return self::error('用户不存在');
        }



        $info->pay_pwd = User::create_pwd( $pwd );

        $info->save();

        return self::success('修改密码成功');

    }

    /**
     * 我的推广
     *
     * @return void
     */
    public function promotion()
    {
        $user_id = session('user_id');
        $data    = User::where('tg_id', $user_id )
                        ->where('status', 1)
                        ->select('id', 'user_nickname', 'user_avatar', 'creditor_status','created_at')
                        ->paginate(15);

        return self::json( $data, '查询成功');
    }

    /**
     * 我的二维码
     *
     * @return void
     */
    public function myUrl()
    {
        return self::json(['url'=>$_SERVER['SERVER_NAME']], '获取成功');
    }

    /**
     * 查询用着状态成功
     *
     * @return 
     */
    public function user_creditor_status()
    {
        $user_id = session('user_id');
        
        $creditor_status = User::where('id', $user_id)->value('creditor_status');

        return self::json(['creditor_status' => $creditor_status], '查询成功');
    }

   

    

}
